package com.ctshk.rpc.order.localfun.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ctshk.common.dto.Result;
import com.ctshk.common.enums.SystemError;
import com.ctshk.common.exception.BusinessException;
import com.ctshk.common.model.TokenUser;
import com.ctshk.common.utils.DateUtil;
import com.ctshk.common.utils.EntityUtil;
import com.ctshk.common.utils.SnowflakeIdWorker;
import com.ctshk.rpc.localfun.dto.LocalFunProductReceiptDTO;
import com.ctshk.rpc.localfun.dto.LocalFunProductSpecAttrDTO;
import com.ctshk.rpc.localfun.req.LocalFunProductDetailReq;
import com.ctshk.rpc.localfun.service.ILocalFunProductService;
import com.ctshk.rpc.order.localfun.dto.LocalFunContentDTO;
import com.ctshk.rpc.order.localfun.dto.LocalFunOrderCollectionReceiptDTO;
import com.ctshk.rpc.order.localfun.dto.LocalFunOrderCollectionWayDTO;
import com.ctshk.rpc.order.localfun.entity.LocalFunOrder;
import com.ctshk.rpc.order.localfun.entity.LocalFunOrderCollection;
import com.ctshk.rpc.order.localfun.entity.LocalFunOrderReceipt;
import com.ctshk.rpc.order.localfun.mapper.LocalFunOrderCollectionMapper;
import com.ctshk.rpc.order.localfun.mapper.LocalFunOrderMapper;
import com.ctshk.rpc.order.localfun.mapper.LocalFunOrderReceiptMapper;
import com.ctshk.rpc.order.localfun.req.LocalFunOrderReceiptAddReq;
import com.ctshk.rpc.order.localfun.req.LocalFunOrderReceiptModifyReq;
import com.ctshk.rpc.order.localfun.req.LocalFunOrderReceiptReq;
import com.ctshk.rpc.order.localfun.service.ILocalFunOrderReceiptService;
import com.ctshk.rpc.system.dto.UserDTO;
import com.ctshk.rpc.system.service.ISysUserService;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
 * @Description
 * @Author wansi <gaylen15527491065@yeah.net>
 * @Date 2021/3/31
 */
@Slf4j
@DubboService
public class LocalFunOrderReceiptServiceImpl extends ServiceImpl<LocalFunOrderReceiptMapper, LocalFunOrderReceipt> implements ILocalFunOrderReceiptService {

    @DubboReference
    private ISysUserService iSysUserService;

    @Autowired
    LocalFunOrderReceiptMapper scenicOrderReceiptMapper;

    @Autowired
    LocalFunOrderMapper scenicOrderMapper;

    @DubboReference
    private ILocalFunProductService localFunProductService;

    @Autowired
    private LocalFunOrderCollectionMapper localFunOrderCollectionMapper;

    @Override
    public Result<Long> add(LocalFunOrderReceiptAddReq scenicOrderReceiptAddReq, TokenUser tokenUser) {
        //生成收据
        LocalFunOrderReceipt scenicOrderReceipt = new LocalFunOrderReceipt();
        scenicOrderReceipt.setOrderId(scenicOrderReceiptAddReq.getOrderId());
        //門市編號+員工編號+年後2位+月日4位+A+時分秒6位+（S）
        Calendar cal = Calendar.getInstance();
        int hour=cal.get(Calendar.HOUR);//小时
        int minute=cal.get(Calendar.MINUTE);//分
        int second=cal.get(Calendar.SECOND);//秒
        String hourNew = String.valueOf(hour);
        String minuteNew = String.valueOf(minute);
        String secondNew = String.valueOf(second);
        if(hourNew.length() <2 ){
            hourNew = "0" + hourNew;
        }
        if(minuteNew.length() <2 ){
            minuteNew = "0" + minuteNew;
        }
        if(secondNew.length() <2 ){
            secondNew = "0" + secondNew;
        }
        String time =  hourNew + minuteNew + secondNew;
        UserDTO userDTO = iSysUserService.loadUserByParam(tokenUser.getId(), 1);
        String receiptNo = userDTO.getDept() + userDTO.getEmployeeNumber() + DateUtil.fmtNum(LocalDate.now()) + "A" + time + "(s)";
        scenicOrderReceipt.setReceiptNo(receiptNo);
        Long id = SnowflakeIdWorker.nextId();
        scenicOrderReceipt.setId(id);
        scenicOrderReceipt.setCreateId(tokenUser.getId());
        scenicOrderReceipt.setGmtCreate(LocalDateTime.now());
        scenicOrderReceipt.setBranch(userDTO.getEmployeeNumber() + "-" + userDTO.getDept());
        LocalFunOrder scenicOrder = scenicOrderMapper.selectById(scenicOrderReceiptAddReq.getOrderId());
        scenicOrderReceipt.setGuest(scenicOrder.getContactName());
        scenicOrderReceipt.setPhone(scenicOrder.getContactMobile());
        scenicOrderReceiptMapper.insert(scenicOrderReceipt);
        return Result.success(scenicOrderReceiptAddReq.getOrderId());
    }

    @Override
    public Result<Long> modify(LocalFunOrderReceiptModifyReq scenicOrderReceiptModifyReq, TokenUser tokenUser) {
        LocalFunOrderReceipt scenicOrderReceipt = EntityUtil.copy(scenicOrderReceiptModifyReq, LocalFunOrderReceipt.class);
        scenicOrderReceipt.setModifiedId(tokenUser.getId());
        scenicOrderReceipt.setGmtModified(LocalDateTime.now());
        return Result.success(scenicOrderReceiptModifyReq.getOrderId());
    }

    @Override
    public Result<LocalFunOrderCollectionReceiptDTO> collectionReceipt(LocalFunOrderReceiptReq localFunOrderReceiptReq, TokenUser user) {
        LocalFunOrder localFunOrder = scenicOrderMapper.selectById(localFunOrderReceiptReq.getOrderId());
        LocalFunOrderCollectionReceiptDTO scenicOrderCollectionReceiptDTO = new LocalFunOrderCollectionReceiptDTO();
        UserDTO userDTO = null;
        try {
            userDTO = iSysUserService.loadUserByParam(user.getId(), 1);
            scenicOrderCollectionReceiptDTO.setBranch(userDTO.getDept());
        } catch (Exception e) {
            throw new BusinessException(SystemError.SYS_502);
        }
        if(localFunOrder != null){
            QueryWrapper<LocalFunOrderReceipt> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("is_deleted",0);
            queryWrapper.eq("order_id",localFunOrder.getId());
            LocalFunOrderReceipt scenicOrderReceipt = scenicOrderReceiptMapper.selectOne(queryWrapper);
            if(scenicOrderReceipt != null){
                scenicOrderCollectionReceiptDTO.setAttention(scenicOrderReceipt.getAttention());
                scenicOrderCollectionReceiptDTO.setRemark(scenicOrderReceipt.getRemark());
                scenicOrderCollectionReceiptDTO.setReceiptNo(scenicOrderReceipt.getReceiptNo());
                scenicOrderCollectionReceiptDTO.setBranch(scenicOrderReceipt.getBranch());
                scenicOrderCollectionReceiptDTO.setGuest(scenicOrderReceipt.getGuest());
                scenicOrderCollectionReceiptDTO.setPhone(scenicOrderReceipt.getPhone());
            }

            LocalFunProductDetailReq scenicProductDetailReq = new LocalFunProductDetailReq();
            scenicProductDetailReq.setId(localFunOrder.getProductId());
            scenicOrderCollectionReceiptDTO.setQueryNumber(localFunOrder.getQueryNumber());

            if(StringUtils.isNotBlank(localFunOrder.getProductTicketsId())){
                String[] split = localFunOrder.getProductTicketsId().split(",");
                scenicProductDetailReq.setAttrId1(Long.valueOf(split[0]));
                log.info("attrIds--->{}" , JSON.toJSONString(split));
                if(split.length > 1 && !"null".equals(split[1])){
                    scenicProductDetailReq.setAttrId2(Long.valueOf(split[1]));
                }
            }
            log.info("attrIds done");
            LocalFunContentDTO contentDTO = new LocalFunContentDTO();
            Result<LocalFunProductReceiptDTO> result = localFunProductService.localFunProductDetail(scenicProductDetailReq);
            if(result.isSuccess()){
                LocalFunProductReceiptDTO scenicProductReceiptDTO = result.getData();
                if(scenicProductReceiptDTO != null){
                    List<LocalFunProductSpecAttrDTO> specAttrDTOS = scenicProductReceiptDTO.getScenicProductSpecAttrDTOList();
                    LocalFunProductSpecAttrDTO localFunProductSpecAttrDTO = specAttrDTOS.stream().findFirst().orElse(null);
                    if(localFunProductSpecAttrDTO != null){
                        contentDTO.setMealName(localFunProductSpecAttrDTO.getAttributeName()+"/"+localFunProductSpecAttrDTO.getSpecName());
                    }
                    contentDTO.setUseTime(1);
                    contentDTO.setName(scenicProductReceiptDTO.getName());
                    scenicOrderCollectionReceiptDTO.setCustomerNotice(scenicProductReceiptDTO.getCustomerNotice());
                    scenicOrderCollectionReceiptDTO.setScenicProductSpecAttrDTOList(scenicProductReceiptDTO.getScenicProductSpecAttrDTOList());
                }
            }
            BigDecimal singleTicket = localFunOrder.getTicketsFee().divide(new BigDecimal(localFunOrder.getTicketNum()));
            contentDTO.setCostPrice(singleTicket);
            contentDTO.setQuantity(localFunOrder.getTicketNum());
            contentDTO.setCostPriceTotal(localFunOrder.getTicketsFee());
            scenicOrderCollectionReceiptDTO.setContent(Lists.newArrayList(contentDTO));

            scenicOrderCollectionReceiptDTO.setMustCollectionAmount(localFunOrder.getReceivableAmount());
            scenicOrderCollectionReceiptDTO.setCollectionAmount(localFunOrder.getOrderAmount());
            scenicOrderCollectionReceiptDTO.setUnionpayDiscount(localFunOrder.getReceivableAmount().subtract(localFunOrder.getOrderAmount()));
//            scenicOrderCollectionReceiptDTO.setQueryNumber(localFunOrder.getQueryNumber());
            //收款记录
            QueryWrapper<LocalFunOrderCollection> scenicOrderCollectionQueryWrapper = new QueryWrapper<>();
            scenicOrderCollectionQueryWrapper.eq("is_deleted",0);
            scenicOrderCollectionQueryWrapper.eq("order_id",localFunOrder.getId());
            List<LocalFunOrderCollection> list = localFunOrderCollectionMapper.selectList(scenicOrderCollectionQueryWrapper);
            if(CollectionUtils.isNotEmpty(list)){
                List<LocalFunOrderCollectionWayDTO> scenicOrderCollectionWayDTOArrayList = new ArrayList<>();
                for(LocalFunOrderCollection collection : list){
                    LocalFunOrderCollectionWayDTO scenicOrderCollectionDTO = EntityUtil.copy(collection,LocalFunOrderCollectionWayDTO.class);
                    scenicOrderCollectionWayDTOArrayList.add(scenicOrderCollectionDTO);
                }
                scenicOrderCollectionReceiptDTO.setScenicOrderCollectionWayDTOArrayList(scenicOrderCollectionWayDTOArrayList);
            }
        }else {
            throw new BusinessException(SystemError.CUSTOM_ORDER_4024);
        }
        return Result.success(scenicOrderCollectionReceiptDTO);
    }
}
